package com.foruo.learn.objectlearn;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Object对象学习
 *
 * 案例是解释对象wait()与notify()方法的使用
 *
 * @author GaoYuan
 * @date 2019/6/18 1:32 PM
 */
public class ObjectLearn {

    AtomicInteger atomicInteger = new AtomicInteger(0);

    public static void main(String[] args) throws Exception{
        ObjectLearn object = new ObjectLearn();
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        executorService.submit(()->{
            object.testMe();
        });
        executorService.submit(()->{
            object.testMe();
        });
        executorService.submit(()->{
            object.testMe();
        });
        executorService.submit(()->{
            object.testMe();
        });
    }

    public synchronized void testMe(){
        try {
            if(atomicInteger.incrementAndGet() > 3){
                Thread.sleep(2000);
                notifyAll();
            }else{
                System.out.println("start" + Thread.currentThread().getId());
                wait(10000);
                System.out.println("end" + Thread.currentThread().getId());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
